const app = getApp();
const https = require('../../utils/https.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    disabled: false,
    gettel: false,
    userPhone: '',
    openid:'',
    session_key: '',
    userInfo: {},
    userInfoLoginResult: null, // 老登录结果
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.userInfoReadyCallback(res)
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this,
        app_logo = wx.getStorageSync('app_logo'),
      login_status = wx.getStorageSync('login_status');
    that.setData({
      login_status,
      app_logo,
      user_info: []
    })
    // 第一步加载
    if(login_status) {
      wx.switchTab({
        url: '/pages/home/home',
      })
    }
    if(!this.data.hasUserInfo){
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  userInfoReadyCallback(res) {
    this.setData({
      userInfo: res.userInfo,
      hasUserInfo: true
    })
  },

  /**
   * 获取用户信息,授权
   */
  getUserInfo(e) {
    this.setData({
      loading: true,
      disabled: true
    })
    if (e.detail.encryptedData) {
      wx.login({
        success: login_res => {
          if (login_res.code) {
            wx.getUserInfo({
              success: info_res => {
                this.userInfoLogin(login_res.code, info_res)
              }
            })
          } else {
            this.setData({
              loading: false,
              disabled: false
            })
            wx.showToast({
              title: '登录失败',
              icon: 'none',
              duration: 1500
            })
          }
        }
      })
    } else {
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
      this.setData({
        loading: false,
        disabled: false
      })
    }
  },
  /**
   * 老的登录，用 getUserInfo
   */
  userInfoLogin(code, {userInfo, iv, encryptedData}) {
    this.setData({
      loading: true,
      disabled: true
    })
    wx.getSetting({
      success: set_res => {
        const {nickName, avatarUrl, gender} = userInfo
        if (set_res.authSetting['scope.userInfo']) {
          https.post('login', {
            code: code,
            nickname: nickName,
            avatar: avatarUrl,
            encryptedData: encryptedData,
            sex: gender,
            iv: iv
          },false,'正在登陆').then(res => {
            const {tel, user_id, openid} = res
            if(tel === '' || !tel){
              this.setData({
                userInfo,
                hasUserInfo: true,
                gettel: true,
                loading: false,
                disabled: false,
                userInfoLoginResult: res
              })
              return
            }
            this.afterLogin({userInfo, user_id, openid, tel})
            this.setData({
              loading: false,
              disabled: false
            })
          }).catch(() => {
            this.setData({
              loading: false,
              disabled: false
            })
          })
        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
          this.setData({
            loading: false,
            disabled: false
          })
        }
      }
    })
  },
  /**
   * 获取用户手机号,授权
   */
  getPhoneNumber: function(e) {

    const that = this;
    this.setData({
      loading: true,
      disabled: true
    })
    wx.login({
      success: function (res) {
        wx.request({
          url: 'https://info.amagich.com/wx/get-openid',
          method:'post',
          data: {
            code: res.code
          },
          success (res) {
            const {openid, session_key} = res.data;
            that.setData({
              openid,
              session_key
            })
            if (e.detail.errMsg === "getPhoneNumber:ok") {
              wx.request({
                url: 'https://info.amagich.com/wx/get-phone',
                data: {
                  encryptData: e.detail.encryptedData,
                  iv: e.detail.iv,
                  session_key: session_key
                },
                method: "post",
                success: function (res) {
                  if(res.data && res.data.resultData && res.data.resultData.phoneNumber) {
                    that.setData({
                      userPhone: res.data.resultData.phoneNumber
                    })
                    that.phoneLogin()
                  } else {
                    wx.showToast({
                      title: '登录失败',
                      icon: 'none'
                    })
                    this.setData({
                      loading: false,
                      disabled: false
                    })
                  }
                },
                fail() {
                  wx.showToast({
                    title: '登录失败',
                    icon: 'none'
                  })
                  this.setData({
                    loading: false,
                    disabled: false
                  })
                }
              })
            } else {
              wx.showToast({
                title: '登录失败',
                icon: 'none'
              })
              this.setData({
                loading: false,
                disabled: false
              })
            }
          },
          fail () {
            wx.showToast({
              title: '登录失败',
              icon: 'none'
            })
            this.setData({
              loading: false,
              disabled: false
            })
          }
        })
      },
      fail : function() {
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
        this.setData({
          loading: false,
          disabled: false
        })
      }
    })
  },
  /**
   * 新的登录 用 getPhoneNumber
   */
  phoneLogin() {
    const that = this;
    const {userPhone, openid,userInfo, userInfoLoginResult} = this.data;
    const {nickName, gender, avatarUrl} = userInfo;
    const {user_id} = userInfoLoginResult
    wx.request({
      url: 'https://info.amagich.com/wx/login',
      data: {
        avatar:	avatarUrl,
        nickname: nickName,
        tel: userPhone,
        openid: openid,
        sex: gender,
        source: 'metro',
      },
      method: "post",
      success: function(res) {
        if(res.data.msg === '登录成功') {
          that.afterLogin({userInfo, tel: userPhone, user_id, openid})
        } else {
          wx.showToast({
            title: '授权失败',
            icon: 'none'
          })
          this.setData({
            loading: false,
            disabled: false
          })
        }
      },
      fail : function() {
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
        this.setData({
          loading: false,
          disabled: false
        })
      }
    })
  },
  /**
   * 把两步登录的结果在一起处理
   */
  afterLogin({user_id, tel, openid, user_info}) {
    app.globalData.user_id = user_id;
    app.globalData.tel = tel;
    app.globalData.openid = openid;
    app.globalData.login_status = true
    wx.setStorageSync('user_info', user_info);
    wx.setStorageSync('tel', tel);
    wx.setStorageSync('openid', openid);
    wx.setStorageSync('user_id', user_id);
    wx.setStorageSync('login_status', true);
    this.setData({
      loading: false,
      disabled: false
    })
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

})
